package main

import (
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/chaincode/shim/ext/statebased"
	"github.com/hyperledger/fabric/protos/peer"
)

type ValidationChaincode struct {

}

func (t *ValidationChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {
	return shim.Success(nil)
}

func (t *ValidationChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	function, args := stub.GetFunctionAndParameters()
	if function == "set" {
		return t.Set(stub, args)
	} else if function == "get" {
		return t.Get(stub, args)
	} else if function == "invoke" {
		return t.invoke(stub, args)
	} else if function == "query" {
		return t.query(stub, args)
	} else {
		return shim.Error("Haven't " + function + " function")
	}
}

func (t *ValidationChaincode) Set(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	key := args[0]
	val := args[1]
	newEp, err := statebased.NewStateEP(nil)
	if err != nil {
		return shim.Error(err.Error())
	}
	err = newEp.AddOrgs(statebased.RoleTypeMember, val)
	if err != nil {
		return shim.Error(err.Error())
	}
	ploicyByte, err := newEp.Policy()
	if err != nil {
		return shim.Error(err.Error())
	}
	err = stub.SetStateValidationParameter(key, ploicyByte)
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success([]byte("Successs"))
}

func (t *ValidationChaincode) Get(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	data, err := stub.GetStateValidationParameter(args[0])
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(data)
}

func (t *ValidationChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success([]byte("Success"))
}

func (t *ValidationChaincode) query(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	data, err := stub.GetState(args[0])
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(data)
}

func main() {
	err := shim.Start(new(ValidationChaincode))
	if err != nil {
		fmt.Printf("error: %s\n", err.Error())
	}
}
